package com.qyhl.cloud.webtv.module_integral.taskcenter;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.style.TextAppearanceSpan;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.snackbar.Snackbar;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.cloud.webtv.module_integral.R;
import com.qyhl.cloud.webtv.module_integral.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.intergral.SignBean;
import com.qyhl.webtv.commonlib.entity.intergral.TaskCenterBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

/**
 * 任务中心
 */
@Route(path = ARouterPathConstant.TASK_CENTER)
public class TaskCenterActivity extends BaseActivity implements TaskCenterContract.TaskCenterView {
    @BindView(R2.id.taskcenter_title)
    TextView taskcenterTitle;
    @BindView(R2.id.taskcenter_toolbar)
    Toolbar taskcenterToolbar;
    @BindView(R2.id.taskcenter_tip_rule)
    TextView taskcenterTipRule;
    @BindView(R2.id.taskcenter_signed_btn)
    Button taskcenterSignedBtn;
    @BindView(R2.id.taskcenter_continuous_day)
    TextView taskcenterContinuousDay;
    @BindView(R2.id.taskcenter_signed_recyclerview)
    RecyclerView taskcenterSignedRecyclerview;
    @BindView(R2.id.taskcenter_head_layout)
    ConstraintLayout taskcenterHeadLayout;
    @BindView(R2.id.taskcenter_divider_line)
    View taskcenterDividerLine;
    @BindView(R2.id.taskcenter_tip_title)
    TextView taskcenterTipTitle;
    @BindView(R2.id.taskcenter_divider_line2)
    View taskcenterDividerLine2;
    @BindView(R2.id.taskcenter_read_reward)
    TextView taskcenterReadReward;
    @BindView(R2.id.taskcenter_read_tip_message)
    TextView taskcenterReadTipMessage;
    @BindView(R2.id.taskcenter_live_reward)
    TextView taskcenterLiveReward;
    @BindView(R2.id.taskcenter_live_tip_message)
    TextView taskcenterLiveTipMessage;
    @BindView(R2.id.taskcenter_comment_reward)
    TextView taskcenterCommentReward;
    @BindView(R2.id.taskcenter_comment_tip_message)
    TextView taskcenterCommentTipMessage;
    @BindView(R2.id.taskcenter_share_reward)
    TextView taskcenterShareReward;
    @BindView(R2.id.taskcenter_share_tip_message)
    TextView taskcenterShareTipMessage;
    @BindView(R2.id.taskcenter_circle_reward)
    TextView taskcenterCircleReward;
    @BindView(R2.id.taskcenter_circle_tip_message)
    TextView taskcenterCircleTipMessage;
    @BindView(R2.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R2.id.taskcenter_sign_reward)
    TextView taskcenterSignReward;
    private TaskCenterPresenter mPresenter;

    private CommonAdapter commonAdapter;

    private List<String> mDataList = new ArrayList<>();

    private String[] contentArray;

    private int[] coverArray;

    private String userName;

    private int signDays = 0;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initTast() {
        BusFactory.getBus().register(this);
        taskcenterTitle.setText("任务中心");
        setSupportActionBar(taskcenterToolbar);

        contentArray = new String[]{"这波优惠很有态度，立戳可领"
                , "不用东奔西走，要优惠点我，应有尽有"
                , "优惠人人有哦，你的券，到手了吗？"
                , "天下是没有免费的午餐，但你可以去领张优惠券"
                , "你优惠，我优惠，来了就优惠"
                , "快来，看看你购物车里哪些宝贝还能省钱"
                , "越用越省惊喜不断，沉迷优惠不可自拔"
                , "爱团购，爱秒杀，更爱优惠劵"};
        coverArray = new int[]{R.drawable.coupon_1_icon, R.drawable.coupon_2_icon, R.drawable.coupon_3_icon,
                R.drawable.coupon_4_icon, R.drawable.coupon_5_icon, R.drawable.coupon_6_icon,
                R.drawable.coupon_7_icon, R.drawable.coupon_8_icon, R.drawable.coupon_9_icon};

        //设置布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 7);
        taskcenterSignedRecyclerview.setLayoutManager(gridLayoutManager);
        for (int i = 0; i < 7; i++) {
            mDataList.add("15");
        }
        taskcenterSignedRecyclerview.setAdapter(commonAdapter = new CommonAdapter<String>(this, R.layout.inter_item_task_center, mDataList) {

            @Override
            protected void convert(ViewHolder viewHolder, String s, int position) {
                TextView textView = viewHolder.getView(R.id.taskcenter_coin);
                textView.setText(s);
                if (position < signDays) {
                    textView.setBackgroundResource(R.drawable.taskcenter_signed_success);
                    textView.setTextColor(getResources().getColor(R.color.global_gray_lv2));
                } else {
                    textView.setBackgroundResource(R.drawable.taskcenter_signed_fail);
                    textView.setTextColor(getResources().getColor(R.color.white));
                }

            }
        });

        userName = CommonUtils.getInstance().getUserName();
        mPresenter.getTaskCenterInfo(userName);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }

    @Override
    protected int getContentView() {
        return R.layout.inter_activity_task_center;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new TaskCenterPresenter(this);
        initTast();
    }

    @Override
    protected void setListener() {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void getSuccess(TaskCenterBean bean) {
        try {
            signDays = Integer.parseInt(bean.getSignDays());
        } catch (Exception e) {
            signDays = 0;
        }
        boolean isSigned = bean.isSignIn();
        mDataList.clear();
        for (int i = 0; i < bean.getCoinList().length; i++) {
            mDataList.add(bean.getCoinList()[i] + "");
        }

        commonAdapter.notifyDataSetChanged();

        if (isSigned) {
            SpanUtils utils = new SpanUtils(this);
            utils.append("明日签到可获取").setSpans(new TextAppearanceSpan(this, R.style.inter_task_center_normal)).append(bean.getTomorrow() + "")
                    .setSpans(new TextAppearanceSpan(this, R.style.inter_task_center_special_two2)).append("金币").setSpans(new TextAppearanceSpan(this, R.style.inter_task_center_normal));
            taskcenterSignedBtn.setText(utils.create());
            taskcenterSignedBtn.setBackgroundResource(R.drawable.taskcenter_signed_btn_bg_on);
        } else if (StringUtils.isEmpty(userName)) {
            taskcenterSignedBtn.setBackgroundResource(R.drawable.taskcenter_signed_btn_bg_off);
            taskcenterSignedBtn.setText("未登录");
        } else {
            taskcenterSignedBtn.setText("签到");
            taskcenterSignedBtn.setBackgroundResource(R.drawable.taskcenter_signed_btn_bg_off);
        }

        SpanUtils spanUtils = new SpanUtils(this);
        spanUtils.append("已连续签到").setSpans(new TextAppearanceSpan(this, R.style.inter_task_center_normal)).append(bean.getSignDays())
                .setSpans(new TextAppearanceSpan(this, R.style.inter_task_center_special_one)).append("天").setSpans(new TextAppearanceSpan(this, R.style.inter_task_center_normal));
        taskcenterContinuousDay.setText(spanUtils.create());

        if (isSigned) {
            taskcenterSignReward.setText("+" + bean.getCoinList()[signDays - 1]);
        } else {
            taskcenterSignReward.setText("+" + bean.getCoinList()[signDays]);
        }


        taskcenterReadReward.setText("+" + bean.getCoinLimit().getNews());
        taskcenterCommentReward.setText("+" + bean.getCoinLimit().getComment());
        taskcenterLiveReward.setText("+" + bean.getCoinLimit().getLive());

        taskcenterShareReward.setText("+" + bean.getCoinLimit().getShare());
        taskcenterShareTipMessage.setText("当您阅读到认同或有趣的资讯时，分享到朋友圈或微信好友，均可获得一定的金币奖励，每日最多可通过分享获得" + bean.getCoinLimit().getShare() + "金币。");

        taskcenterCircleReward.setText("+" + bean.getCoinLimit().getSociety());
        taskcenterCircleTipMessage.setText("在本地圈发布积极健康的内容，即可获得" + bean.getCoinLimit().getSociety() + "金币，每天仅限一次。");


    }

    /**
     * 获取任务中心内容出错
     *
     * @param msg 信息
     */
    @Override
    public void getError(String msg) {
        Toasty.normal(this, msg).show();
    }

    /**
     * 网络出错
     *
     * @param msg 提示
     */
    @Override
    public void getNetError(String msg) {
        Snackbar.make(rootLayout, msg, Snackbar.LENGTH_LONG).setAction("设置", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(
                                Settings.ACTION_WIFI_SETTINGS),
                        0);
            }
        }).show();
    }

    /**
     * 签到成功
     *
     * @param bean 数据
     */
    @Override
    public void doSignSuccess(SignBean bean) {
        ActionLogUtils.getInstance().onEvent(ActionConstant.SIGN_IN);
        String userName = CommonUtils.getInstance().getUserName();
        mPresenter.getTaskCenterInfo(userName);
        new OtherDialog.Builder(this)
                .setContentView(R.layout.inter_dialog_tastcenter_layout)
                .setDismissButton(R.id.dialog_cancel)
                .setWidth(0.8f)
                .setText(R.id.dialog_coin_add, "+" + bean.getCoin())
                .setText(R.id.dialog_ticket_content, contentArray[new Random().nextInt(8)])
                .setImageResource(R.id.dialog_ticket_cover, coverArray[new Random().nextInt(9)])
                .setCanceledOnTouchOutside(false)
                .setOnClickListener(R.id.dialog_ticket_commit, "去领券", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //跳转至优惠券首页
                        RouterManager.router(ARouterPathConstant.COUPON_HOME);
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.SIGN_IN_HOME, ActionConstant.COUPON_HOME);
                    }
                }).show();
    }

    /**
     * 签到 失败
     *
     * @param msg 信息
     */
    @Override
    public void doSignFailure(String msg) {
        Toasty.normal(this, msg).show();
    }

    /**
     * eventBus 接收器
     *
     * @param event 登录事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        userName = CommonUtils.getInstance().getUserName();
        if (event != null) {
            if (event.isLogin()) {//登录
                mPresenter.getTaskCenterInfo(userName);
            }
        }
    }


    @OnClick({R2.id.taskcenter_signed_btn})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.taskcenter_signed_btn) {
            switch (taskcenterSignedBtn.getText().toString()) {
                case "未登录":
                    RouterManager.routerLogin(this, 0);
                    break;
                case "签到":
                    String userName = CommonUtils.getInstance().getUserName();
                    mPresenter.doSign(userName);
                    break;
                default:
                    break;
            }

        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.SIGN_IN_HOME);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.SIGN_IN_HOME);
    }
}
